const Router = require('koa-router');
const { Patient } = require('../models/index');
const router = new Router({
  prefix: '/api/patient'
});

// 获取患者列表
router.get('/list', async (ctx) => {
  try {
    const res = await Patient.findAll({
      attributes: ['id', 'name', 'gender', 'birthDate', 'memberRelationship', 'idNumber', 'phone']
    });
    ctx.body = {
      code: 200,
      message: '获取患者列表成功',
      data: res
    };
  } catch (error) {
    ctx.body = {
      code: 500,
      message: '获取患者列表失败',
      error: error.message
    };
  }
});

// 添加新患者
router.post('/add', async (ctx) => {
  try {
    const { name, gender, birthDate, memberRelationship, idNumber, phone } = ctx.request.body;
    
    // 基本验证
    if (!name) {
      ctx.body = {
        code: 400,
        message: '患者姓名不能为空'
      };
      return;
    }
    
    const newPatient = await Patient.create({
      name,
      gender,
      birthDate: birthDate ? new Date(birthDate) : null,
      memberRelationship,
      idNumber,
      phone
    });
    
    ctx.body = {
      code: 200,
      message: '添加患者成功',
      data: newPatient
    };
  } catch (error) {
    ctx.body = {
      code: 500,
      message: '添加患者失败',
      error: error.message
    };
  }
});
//删除患者
router.delete('/delete/:id', async (ctx) => {
  try {
    const { id } = ctx.params;
    const patient = await Patient.findByPk(id);
    if (!patient) {
      ctx.body = {
        code: 404,
        message: '患者不存在'
      };
      return;
    }
    await patient.destroy();
    ctx.body = {
      code: 200,
      message: '删除患者成功'
    };
  } catch (error) {
    ctx.body = {
      code: 500,
      message: '删除患者失败',
      error: error.message
    };
  }
});
//根据id查询患者
router.get('/:id', async (ctx) => {
  try {
    const { id } = ctx.params;
    const patient = await Patient.findByPk(id);
    if (!patient) {
      ctx.body = {
        code: 404,
        message: '患者不存在'
      };
      return;
    }
    ctx.body = {
      code: 200,
      message: '获取患者成功',
      data: patient
    };
  } catch (error) {
    ctx.body = {
      code: 500,
      message: '获取患者失败',
      error: error.message
    };
  }
});
//更新患者
router.put('/update/:id', async (ctx) => {
  try {
    const { id } = ctx.params;
    const { name, gender, birthDate, memberRelationship, idNumber, phone } = ctx.request.body;
    const patient = await Patient.findByPk(id);
    if (!patient) {
      ctx.body = {
        code: 404,
        message: '患者不存在'
      };
      return;
    }
    await patient.update({
      name,
      gender,
      birthDate: birthDate ? new Date(birthDate) : null,
      memberRelationship,
      idNumber,
      phone
    });
    ctx.body = {
      code: 200,
      message: '更新患者成功',
      data: patient
    };
  } catch (error) {
    ctx.body = {
      code: 500,
      message: '更新患者失败',
      error: error.message
    };
  }
});

module.exports = router;